package com.fpost.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.fpost.constants.ActionConstants;
import com.fpost.constants.CommonConstants;
import com.fpost.domain.Article;
import com.fpost.form.dto.UserDTO;
import com.fpost.manager.ArticleManager;
import com.fpost.security.ActionSecurityUtils;
import com.fpost.util.ActionUtils;
import com.fpost.util.CommonUtils;

public class DeleteArticleAction extends Action {
	
	private static Logger log = Logger.getLogger(DeleteArticleAction.class);
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//set current path in session
		CommonUtils.setCurrentPathInSession(request, mapping);
		
		String forward = ActionConstants.SUCCESS;		

		try {
			String articleIdStr = request.getParameter("articleId");
			long articleId = Long.parseLong(articleIdStr);
			
			UserDTO userDTO = ActionSecurityUtils.getUserDTO_fromSession(request);
			if (userDTO == null) {
				forward = ActionConstants.LOGIN;
			} else if (ActionSecurityUtils.isDeleteAllowed(Long.parseLong(userDTO.getUserId()), articleId)) {
				Article article = new ArticleManager().getArticleById(articleId);
				article.setDeleted(true);
				new ArticleManager().saveOrUpdate(article);
				ActionUtils.setErrorMessage(request, "info.article.successfully.deleted");
				forward = ActionConstants.SUCCESS;
			} else {
				ActionUtils.setErrorMessage(request, "error.article.delete.not.allowed");
				forward = ActionConstants.FAILURE;
			}			
		} catch (NumberFormatException e) {
			log.error(e.getMessage());
			ActionUtils.setErrorMessage(request, "error.article.delete.failed");
			forward = ActionConstants.FAILURE;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
			forward = ActionConstants.SYSTEM_FAILURE;
		}
		return mapping.findForward(forward);
	}
		
}
